package com.rongshu.view.discovery.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.view.base.AdapterListener;
import com.utils.SPUtils;
import com.utils.constants.SPKey;

import java.util.ArrayList;
import java.util.List;

/**
 * created by zhengweis on 2018/11/1.
 * description：发现-搜索页面-搜索历史
 */
public class RecommendHistoryAdapter extends RecyclerView.Adapter<RecommendHistoryAdapter.ViewHolder> {
    private Context context;
    private List<String> list = new ArrayList<>();
    private AdapterListener listener;

    public RecommendHistoryAdapter(Context context) {
        this.context = context;
    }

    public void setData(List<String> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public void setAdapterListener(AdapterListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter_recommend_history, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
        viewHolder.title.setText(list.get(i));
        viewHolder.clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.remove(i);
                String string = SPUtils.arrayList2String(list);
                SPUtils.putPreferences(SPKey.SEARCH_HISTORY, string);
                notifyDataSetChanged();
                if (list.size() == 0 || list == null) {
                    listener.callBack("clearData");
                }
            }
        });
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.callBack(list.get(i));
            }
        });
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView title;
        private RelativeLayout clear;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.recommend_history_title);
            clear = itemView.findViewById(R.id.recommend_history_clear);
        }
    }
}
